#!/usr/bin/env node

// 简单测试脚本：从指定 HTML 中解析参考编号
// 逻辑与 runner 一致：
// 1) 优先 DOM 相邻单元格：label 为 參考編號/参考编号 的下一单元格 <b> 文本
// 2) 回退全文正则：冒号可选、允许空格/连字符，保存前去空格/连字符

import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import { load as loadHtml } from 'cheerio'

function extractReferenceNumberFromHtml(html) {
  const $ = loadHtml(html)
  let ref = ''

  // 1) DOM 相邻单元格优先
  try {
    $('td,th').each((_, el) => {
      const label = ($(el).text() || '').replace(/\s+/g, '')
      if (/^(?:參考編號|参考编号)$/.test(label)) {
        const next = $(el).next()
        if (next && next.length) {
          const raw = (next.find('b').first().text() || next.text() || '').trim()
          if (raw) {
            ref = raw.replace(/[\s-]+/g, '')
            return false // break
          }
        }
      }
    })
  }
  catch {}

  // 2) 回退：全文正则
  if (!ref) {
    const bodyText = ($('body').text() || '')
    const m = bodyText.match(/(?:參考編號|参考编号)\s*(?:[：:]\s*)?([A-Z0-9][A-Z0-9\s-]+)/)
    if (m)
      ref = (m[1] || '').replace(/[\s-]+/g, '')
  }

  return ref
}

async function main() {
  // 允许通过命令行传入相对路径；默认为仓库自带示例
  const rel = process.argv[2] || path.join(
    'website_resources',
    'tdabs_external',
    '新增预约_5_步骤三_AdminServlet_tchinese_cmdSubmitAppointmentAction.html',
  )
  const filePath = path.resolve(process.cwd(), rel)
  const html = await fs.readFile(filePath, 'utf8')

  const ref = extractReferenceNumberFromHtml(html)
  console.log(JSON.stringify({ file: filePath, referenceNumber: ref }, null, 2))

  // 基于仓库样例的期望断言：5122 5091 1100 2512 -> 去空格
  const expected = '5122509111002512'
  if (ref === expected) {
    console.log('TEST_PASS: referenceNumber matches expected')
    process.exit(0)
  }
  else {
    console.error(`TEST_FAIL: expected ${expected} but got ${ref || '(empty)'}`)
    process.exit(1)
  }
}

main().catch((err) => {
  console.error('ERROR:', err && err.message ? err.message : err)
  process.exit(2)
})
